import { JSEncrypt } from 'jsencrypt'
import { Base64 } from 'js-base64'
import { Service } from '../services/service'
import store from '@/store'
export const formaturl = (data, isEncode) => {
  const paramsPairArr = []
  for (const key in data) {
    const param = isEncode ? decodeBase64(data[key]) : data[key]
    isDef(param) && paramsPairArr.push(`${key}=${param}`)
  }
  return '?' + paramsPairArr.join('&')
}
export const isDef = function(d) {
  const type = Object.prototype.toString.call(d)
  let ret = false
  switch (type) {
    case '[object Object]':
      ret = Object.keys(d).length !== 0
      break
    case '[object Array]':
      ret = d.length !== 0
      break
    default:
      ret = ![null, undefined, ''].includes(d)
      break
  }
  return ret
}
export const formatFilterId = (filterId) => {
  const keys = Object.keys(filterId)
  return keys.length === 0
    ? ''
    : '&' +
        keys
          .map((item) => {
            return `${item}=${filterId[item]}`
          })
          .join('&')
}
export const encryptPassword = function(password) {
  const publickey =
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbbOc/NMyfOUvDzYtVUdDDLONe06vt80HQ0uXckgs/fytU78ICFxQVzpeNxNAlSJiFtrBhJKcUzPoGUVXSstgSMUTIEQqj9bfPbbujoy7OboLddnppDnnj9v6/QdZqtLs3TwXVIglf0JUr1u5qKR0kGKDKogttI/UqulGoSotAywIDAQAB'
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publickey)
  return encryptor.encrypt(password)
}
export async function getLoginCode() {
  const random = Math.random().toString()
  store.commit('login/setDeviceId', random)
  const retData = await Service({
    url:
      '/hanyun/authorization-server/validata/code' +
      formaturl({ deviceId: random }),
    method: 'get',
    responseType: 'arraybuffer',
    data: {}
  })
  const blob = new Blob([retData])
  return blob
}

export const encodeBase64 = str => {
  return Base64.encode(str)
}

export const decodeBase64 = str => {
  return Base64.decode(str)
}
